<?php
namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
// use App\Models\Certificate;
// use App\Models\Member;
use Illuminate\Support\Facades\Http;
use Auth;
use LaravelJsTan\Facades\JsTan;
use JsTan\Client;
use JsTan\Route;
use JsTanInIt\JsTanInIt;
use Log;
use App\Services\JsTan\Xinshida;
use App\Services\Certificate;

class XinShiDaController extends Controller
{

    /**
     * @api {post} /xinshida/test
     * 聚水潭测试
     */
    public function test(Request $request)
    {
        // $authUrl = JsTan::Client()->createAuthUrl();
        // $response = JsTan::Client()->request(
        //     Route::QUERY_SHOPS,[
        //         'page_index' => 1,
        //         'page_size' => 10
        //     ]
        // );
        // dd($authUrl, $response);

        $client = Client::getInstance(config('jsTanXsd'));
        $route = Route::getInstance();


        // $response = $client->getAccessToken('001');



        // 店铺资料上传
        $shop_items = [
            'items' => [
                0=> [
                    "sku_id" => "0708062",
                    "i_id" => "1SFCC0708062",
                    "shop_sku_id" => "1038",
                    'sku_code' => '1038',
                    'shop_i_id' => '1SFCC0708062',
                    'shop_sku_id' => '0708062',
                    "original_sku_id" => "1038",
                    "name" => "PM Fitline 青柠小红",
                    "shop_properties_value" => "1罐;顺丰直邮CC",
                    "sku_sign" => "0708062",
                    "shop_id" => 17292311,
                    "shop_sku_url" => "https://www.duesselpharm.com/goods.php?id=1038",
                ],
            ],
        ];
        // $response = JsTan::Client()->request(
        //     Route::UPLOAD_SKUMAP, $shop_items
        // );
        // $response = json_decode($response, 1);
        // dd(config('jsTan'),$response);



        // 订单上传
        $order_params = [
            'shop_id' => 17292311,
            'so_id' => '20241129561631234',
            'order_date' => '2024-11-28 12:12:12',
            'shop_status' => 'WAIT_SELLER_SEND_GOODS',
            'shop_buyer_id' => 'lu_jiu',
            'receiver_state' => '上海',
            'receiver_city' => '上海市',
            'receiver_district' => '徐汇区',
            'receiver_address' => '王家厍路55弄',
            'receiver_name' => '路久',
            'receiver_phone' => '13564137019',
            'receiver_mobile' => '13564137019',
            'receiver_country' => 'CN',
            // 'receiver_zip' => 200211,
            'pay_amount' => 105.04,
            'freight' => 0.00,
            'buyer_message' => '买家留言',
            'remark' => '卖家备注',
            'items' => [
                0 => [
                    'sku_id' => '0708062',
                    'shop_sku_id' => '0708062',
                    'shop_i_id' => '1SFCC0708062',
                    'amount' => 105.04,
                    'base_price' => 105.04,
                    'qty' => 1,
                    'name' => 'PM Fitline 青柠小红',
                    'outer_oi_id' => '1038',

                ],

            ],

            'pay' => [
                'outer_pay_id' => '155775985878733471',
                'pay_date' => '2024-11-28 12:12:12',
                'payment' => '线下',
                'seller_account' => '22',
                'buyer_account' => '22',
                'amount' => 105.04,
            ],
            'card' => [
                'name' => '张三',
                'card_id' => '412823199010102121',
            ],
        ];
        $response = JsTan::Client()->request(
            Route::UPLOAD_ORDERS, [$order_params]
        );
        $response = json_decode($response, 1);
        dd(config('jsTan'),$response);
        // array:3 [ // app/Http/Controllers/Api/JsTanController.php:177
        //   "msg" => "执行成功"
        //   "code" => 0
        //   "data" => array:2 [
        //     "datas" => array:1 [
        //       0 => array:5 [
        //         "msg" => "成功"
        //         "issuccess" => true
        //         "so_id" => "20241129561631234"
        //         "o_id" => 163877
        //         "split_id" => null
        //       ]
        //     ]
        //     "requestId" => null
        //   ]
        // ]

        /**
        * 刷新access_token （请求示例）
        */
        // $response = $client->refreshToken('001');

    }

    /**
     * @api {post} /xinshida/receive_order
     * 店铺商品资料上传
     */
    public function receive_order(Request $request)
    {
        $request = $request->all();
        // $request = file_get_contents("php://input");
        Log::info('xsd_receive_order_request:'. json_encode($request));
        // $request = '{"add_time":"1554065310","address":"\u56de\u5174\u8857\u9053","appid":"1000001","card_img":"{\"card1\":\"http:\\\/\\\/www.xxx.com\\\/Public\\\/uploads\\\/Img\\\/xxx\\\/xxx.jpg\",\"card2\":\"http:\\\/\\\/www.xxx.com\\\/Public\\\/uploads\\\/Img\\\/xxx\\\/xxx.jpg\"}","city":"\u91cd\u5e86\u5e02","consignee":"\u5f20\u4e09","district":"\u91cd\u5e86\u5e02","goods_amount":"52.00","goodsdetails":"[{\"goods_name\":\"\\u3010\\u9999\\u6e2f\\u76f4\\u90ae\\u3011\\u8d44\\u751f\\u5802\\u5929\\u7136\\u70ad\\u6e05\\u723d\\u63a7\\u6cb9\\u6d17\\u9762\\u5976\\u9ed1\\u8272\",\"goods_attr_number\":\"2\",\"goods_attr_name\":\"2\\u652f\",\"supplies_sn\":\"1G5000hy\",\"term\":\"2021-11\\\/2021-11\",\"goods_costprice\":\"52.00\",\"goods_price\":\"26.00\",\"goods_number\":\"1\"}]","nric":"15161651616161151","order_amount":"62.00","order_sn":"2210818135216694588","order_type":"2","pay_name":"\u901a\u8054\u652f\u4ed8","pay_time":"1554065310","province":"\u91cd\u5e86\u5e02","shipping_fee":"10.00","tel":"18710011111","timestamp":"1748179035","sign":"57a7f71157cb36d858b837bad52780f2"}';
        // $request = json_decode($request, 1);

        // 验签名
        $check_sign = Xinshida::checkSign($request);
        if (!$check_sign)
        {
            $result = ['code' => '1111', 'message' => '验签失败'];
        }

        $card_img = json_decode($request['card_img'], 1);
        $card_img['consignee'] = $request['consignee'];
        $card_img['nric'] = $request['nric'];

        $goodsdetails = json_decode($request['goodsdetails'], 1);
        // dd($request, $request['card_img'],$card_img, $request['goodsdetails'], $goodsdetails);
        // Log::info('receive_order_request:' . json_encode($request));

        if ($card_img['card1'] && $card_img['card2'])
        {
            // 更新身份信息
            $msg = '';
            $check_cert = Certificate::checkCert($card_img, $msg);

            if (!$check_cert)
            {
                // 同步身份证
                $up_cert = Certificate::upCertInfo($card_img, $msg);
                if ($up_cert)
                {
                    $msg = "身份信息已上传";
                }
            }
            else
            {
                $msg = "身份信息已上传";
            }
        }

        $remark = $request['consignee'] . '   ' . $request['nric'];
        $remark .= "\r\n". $request['consignee'] . ' ' . $request['tel'] . ' ' . $request['province'] . $request['city'] . $request['district'] . $request['address'];
        $remark .= "\r\n".$msg;

        $items = [];
        foreach ($goodsdetails as $key => $value)
        {
            $items[$key] = [
                'sku_id' => $value['supplies_sn'],
                'shop_sku_id' => $value['supplies_sn'],
                'shop_i_id' => $value['supplies_sn'],
                'properties_value' => trim($value['goods_attr_name']),
                'amount' => (float)$value['goods_price'] * $value['goods_number'],
                'base_price' => (float)$value['goods_costprice'],
                'qty' => intval($value['goods_number']),
                'name' => $value['goods_name'],
                'outer_oi_id' => $value['supplies_sn'].'_'. $value['goods_attr_number'],
            ];
        }

        // 订单上传
        $order_params = [
            'shop_id' => 18324794,
            'so_id' => $request['order_sn'],
            'order_date' => date('Y-m-d H:i:s', $request['add_time']),
            'shop_status' => 'WAIT_SELLER_SEND_GOODS',
            'shop_buyer_id' => $request['appid'],
            'receiver_state' => $request['province'],
            'receiver_city' => $request['city'],
            'receiver_district' => $request['district'],
            'receiver_address' => $request['address'],
            'receiver_name' => $request['consignee'],
            'receiver_phone' => $request['tel'],
            'receiver_mobile' => $request['tel'],
            'receiver_country' => 'CN',
            // 'receiver_zip' => 200211,
            'pay_amount' => (float)$request['order_amount'],
            'freight' => (float)$request['shipping_fee'],
            'buyer_message' => '',
            'remark' => $remark,
            'items' => $items,
            'pay' => [
                'outer_pay_id' => $request['pay_time'],
                'pay_date' => date('Y-m-d H:i:s', $request['pay_time']),
                'payment' => $request['pay_name'],
                'seller_account' => '未知',
                'buyer_account' => '未知',
                'amount' => (float)$request['order_amount'],
            ],
            'card' => [
                'name' => $request['consignee'],
                'card_id' => $request['nric'],
            ],
        ];
        // dd($request, $order_params);

        $client = Client::getInstance(config('jsTanXsd'));
        // $route = Route::getInstance();

        $response = $client->request(
            Route::UPLOAD_ORDERS, [$order_params]
        );
        $response = json_decode($response, 1);
        Log::info('xsd_receive_order_params:'. json_encode($order_params));
        Log::info('xsd_receive_order_response:'. json_encode($response));
        // dd(config('jsTanXsd'), $response);

        if ($response['code']==0 && $response['data']['datas'][0]['issuccess']==true)
        {
            $result = ['code' => '0000', 'message' => '同步成功'];
        }
        else
        {
            $result = ['code' => '1111', 'message' => '同步失败'];
        }

        return json_encode($result);
    }

    /**
     * @api {post} /xinshida/order_delivery
     * 接收:订单发货
     */
    public function order_delivery(Request $request)
    {
        $request = $request->all();
        Log::info('xsd_order_delivery_request:'. json_encode($request));

        //{"o_id":1,"l_id":"test","so_id":"test","lc_id":"test","order_from":"test","wms_co_id":0,"logistics_company":"test","send_date":"2024-12-08 23:46:01.687","items":[{"oi_id":1,"sku_id":"test","qty":1,"name":"test","outer_oi_id":"test","so_id":"test"}],"ts":"1733672761","partnerid":"erp","method":"logistics.upload","sign":"4df98d6c1534e6d2b644cfb0478e6b89"}

        // {"o_id":167859,"l_id":"DEUHYD400066038247EU","so_id":"2023022852799","lc_id":"\u8d27\u6613\u8fbe__12","order_from":"open","wms_co_id":13659696,"logistics_company":"\u4e5d\u8058","send_date":"2024-12-08 23:52:37.019",items":[],"ts":"1733673157","partnerid":"erp","method":"logistics.upload","sign":"ab007bad85ab2107cb5f1ec83d2cf9e9"}

        // $request = [
        //     'so_id'=> "45646565",
        //     'lc_id'=> "EMS",
        //     'logistics_company'=> "EMS",
        //     'l_id'=> "555522001",
        // ];

        // $request = '{"o_id":254244,"l_id":"DEUHYD500595103536EU","so_id":"br250527157140790243","lc_id":"C_001","order_from":"open","wms_co_id":13659696,"logistics_company":null,"send_date":"2025-05-27 16:36:20.331","items":[{"oi_id":284395,"sku_id":"4056631003459BJ1","qty":2,"name":"Aptamil \u7231\u4ed6\u7f8e\u767d\u91d1\u7248\u5976\u7c89 1\u6bb5","outer_oi_id":"4056631003459BJ1_2","so_id":"br250527157140790243"}],"ts":"1748334980","partnerid":"erp","method":"logistics.upload","sign":"fd2e9b74ff87540566e53df036bdf9cb"}';
        // $request = json_decode($request, 1);
        // dd($request);
        $msg = '';
        $res = Xinshida::orderDelivery($request, $msg);

        Log::info('xsd_order_delivery_res:'. json_encode($res));
        // dd('sss',$res, $msg);
        if (!$res)
        {
            $result = ['code' => 500, 'msg' => $msg];
        }
        else
        {
            $result = ['code' => 0, 'msg' => '成功'];
        }

        return json_encode($result);
    }

}
